<!-- 搜索表单 -->
<template>
  <a-card :bordered="false">
    <!-- 表格 -->
    <ele-pro-table ref="oceanFeeTableRef" row-key="id" :columns="columns" :datasource="datasource" :scroll="{ x: 1000 }"
      :needPage="false">
      <template #toolbar>
        <a-space>
          <a-button v-if="oceanId > 0" type="primary" @click="oceanFeeOpenEdit(null, 'receivable')"
            v-any-permission="['order:oceanFee:save']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>应收</span>
          </a-button>
        </a-space>
        <a-space class="space">
          <a-button v-if="oceanId > 0" class="re" @click="oceanFeeOpenEdit(null, 'payable')"
            v-any-permission="['order:oceanFee:save']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>应付</span>
          </a-button>
        </a-space>
        <span style="font-size: 17px;">
          <span style="color:#dea32c;">应收USD {{ fee.receivable.USD }} 应付USD {{ fee.payable.USD }} </span>
          应收CNY {{ fee.receivable.CNY }} 应付CNY {{ fee.payable.CNY }}
          <span style="color:#f47920;"> 利润USD {{ fee.receivable.USD - fee.payable.USD }} </span>
          <span style="color:#d71345;"> 利润CNY {{ fee.receivable.CNY - fee.payable.CNY }}</span>
        </span>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <a-tag v-if="record.type == '应收'" color="blue">
            {{ record.type }}
          </a-tag>
          <a-tag v-if="record.type == '应付'" color="red">
            {{ record.type }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="oceanFeeOpenEdit(record)" v-any-permission="['order:oceanFee:update']">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除此项吗？" @confirm="oceanFeeRemove(record)">
              <a class="ele-text-danger" v-any-permission="['order:oceanFee:remove']">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </a-card>
  <!-- 海运运费添加、修改弹窗 -->
  <ele-modal :width="460" v-model:visible="oceanFeeVisible_modal" :confirm-loading="loading"
    :title="oceanFeeIsUpdate ? '修改' + payable_receivable_type + '海运运费' : '' + payable_receivable_type + '海运运费'"
    :body-style="{ paddingBottom: '8px' }" @ok="oceanFeeSave" :maskClosable="false">
    <a-form ref="oceanFeeFormRef" :model="oceanFeeForm" :rules="oceanFeeRules"
      :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
      <a-form-item label="费用方向" name="type">
        <a-input allow-clear :maxlength="200" placeholder="费用方向" v-model:value="oceanFeeForm.type" autocomplete="off"
          disabled="true" />
      </a-form-item>
      <a-form-item label="费用名称" name="feeName">
        <a-auto-complete v-model:value="oceanFeeForm.feeName_val" :options="feeNameOptions" placeholder="请输入"
          @select="feeName_onSelect" @search="feeName_onSearch" @blur="feeName_blur" allow-clear />
      </a-form-item>
      <a-form-item label="金额" name="price">
        <a-input allow-clear :maxlength="200" placeholder="请输入金额" v-model:value="oceanFeeForm.price" autocomplete="off" />
      </a-form-item>
      <a-form-item label="模块" name="feeModules">
        <a-input allow-clear :maxlength="200" placeholder="请输入模块" v-model:value="oceanFeeForm.feeModules"
          autocomplete="off" disabled="disabled" />
      </a-form-item>
      <a-form-item label="抬头" name="invoicename">
        <a-auto-complete v-model:value="oceanFeeForm.invoicename_val" :options="invoicenameOptions" placeholder="请输入"
          @select="invoicename_onSelect" @search="invoicename_onSearch" @blur="invoicename_blur" allow-clear />
      </a-form-item>
      <a-form-item label="开票" name="invoicestate">
        <a-select v-model:value="oceanFeeForm.invoicestate" placeholder="请选择" allow-clear>
          <a-select-option value="1">开票</a-select-option>
          <a-select-option value="0">不开票</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="币种" name="currency">
        <a-select v-model:value="oceanFeeForm.currency" placeholder="请选择" allow-clear @change="currencyChange">
          <a-select-option value="CNY">CNY</a-select-option>
          <a-select-option value="USD">USD</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="汇率" name="exchangeRate">
        <a-input allow-clear :maxlength="200" placeholder="请输入汇率" v-model:value="oceanFeeForm.exchangeRate"
          autocomplete="off" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-input allow-clear :maxlength="200" placeholder="请输入备注" v-model:value="oceanFeeForm.remark"
          autocomplete="off" />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';

import { listMaintainFeeAttachsSel } from '@/api/order/maintainFeeAttach';
import { listInvoiceSel } from '@/api/order/customer';
import { pageOceanFee, removeOceanFee, addOceanFee, updateOceanFee } from '@/api/order/oceanFee';
import { listSettings } from '@/api/order/settings';
import { TIME_OUT } from '@/config/damon';


// 表格实例
const oceanFeeTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (oceanFeeTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    // sorter: true
  },
  {
    title: '费用名称',
    dataIndex: 'feeName',
    key: 'feeName',
    // sorter: true
  },
  {
    title: '金额',
    dataIndex: 'price',
    key: 'price',
    // sorter: true
  },
  {
    title: '模块',
    dataIndex: 'feeModules',
    key: 'feeModules',
    // sorter: true
  },
  {
    title: '抬头',
    dataIndex: 'invoicename',
    key: 'invoicename',
    // sorter: true
  },
  {
    title: '开票',
    dataIndex: 'invoicestate',
    key: 'invoicestate',
    // sorter: true
  },
  {
    title: '币种',
    dataIndex: 'currency',
    key: 'currency',
    // sorter: true
  },
  {
    title: '汇率',
    dataIndex: 'exchangeRate',
    key: 'exchangeRate',
    // sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: oceanFeeWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

let rate_options = reactive([])
listSettings({ 'typeM': 'exchange_rate' }).then(msg => {
  rate_options = msg
}).catch((e) => {
})
const currencyChange = (val) => {
  if (val == 'USD') {
    rate_options.forEach(ele => { if (ele.label == 'USD') { oceanFeeForm.exchangeRate = ele.value + '' } })
  } else if (val == 'CNY') {
    oceanFeeForm.exchangeRate = '1'
  }
}
let oceanId = ref(0)
let ocean = reactive(null)
// 表格数据源
let fee = reactive({
  'total': 0,
  'receivable_t': 0,
  'payable_t': 0,
  'payable': { 'USD': 0, 'CNY': 0 },
  'receivable': { 'USD': 0, 'CNY': 0 },
})
const datasource = async ({ page, limit, where, orders }) => {
  if (oceanId.value == 0) {
    return new Promise((resolve) => {
      resolve({ count: 0, list: [] })
    })
  }
  limit = 1000
  fee.total = 0
  fee.receivable_t = 0
  fee.payable_t = 0
  fee.payable = { 'USD': 0, 'CNY': 0 }
  fee.receivable = { 'USD': 0, 'CNY': 0 }

  let data_temp = {}
  await pageOceanFee({ ...where, ...orders, page, limit }).then((msg) => {
    data_temp = msg
    msg.list.forEach(element => {
      if (element.type == '应收') {
        if (fee.receivable[element.currency] != undefined) {
          // fee.receivable[element.currency] += parseFloat(element.price) * parseFloat(element.exchangeRate)
          fee.receivable[element.currency] += parseFloat(element.price)
        } else {
          fee.receivable[element.currency] = parseFloat(element.price)
        }
      } else if (element.type = '应付') {
        if (fee.payable[element.currency] != undefined) {
          fee.payable[element.currency] += parseFloat(element.price)
        } else {
          fee.payable[element.currency] = parseFloat(element.price)
        }
      }
    });
    // for (let key in fee.receivable) {
    //   fee.receivable_t += fee.receivable[key]
    // }
    // for (let key in fee.payable) {
    //   fee.payable_t += fee.payable[key]
    // }
    // fee.total = fee.receivable_t-fee.payable_t
  }).catch((e) => {
  });
  return new Promise((resolve) => {
    resolve(data_temp)
  })


};

/* 搜索 */
// {
//     'oceanId': oceanCurrent.value.id,
//     'invoice': {
//       'company': oceanCurrent.value.customer,
//       'bookingAgent': oceanCurrent.value.bookingAgent,
//     }
//   }
const oceanFeeReload = (ocean2) => {
  oceanId.value = ocean2.oceanId
  ocean = ocean2
  oceanFeeWhere.oceanId = oceanId.value
  oceanFeeTableRef?.value?.reload({ page: 1, where: oceanFeeWhere });
};

defineExpose({ oceanFeeReload })

/*  重置 */
const oceanFeeReset = () => {
  resetFields();
  oceanFeeReload(ocean);
};

/* 删除单个 */
const oceanFeeRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeOceanFee(record.id).then((msg) => {
    hide();
    message.success(msg);
    oceanFeeReload(ocean);
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const oceanFeeCurrent = ref(null);

// 弹窗是否打开
const oceanFeeVisible_modal = ref(false);

// 是否是修改
const oceanFeeIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const oceanFeeFormRef = ref(null);

// 表单数据
const { form: oceanFeeForm, resetFields: oceanFeeResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const oceanFeeRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});


//新建海运费用 默认显示抬头  防止重复刷新
// {
//     'oceanId': oceanCurrent.value.id,
//     'invoice': {
//       'company': oceanCurrent.value.customer,
//       'bookingAgent': oceanCurrent.value.bookingAgent,
//     }
//   }
let timeout = 0
const feeNameOptions = ref([]);
const feeName_onSearch = searchText => {
  clearTimeout(timeout)
  timeout = setTimeout(() => {
    listMaintainFeeAttachsSel({ 'name': searchText }).then(msg => {
      msg.map((element) => {
        element.label = element.label + ' -' + element.module
        element.value = element.value + '-' + element.price
      })
      feeNameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const feeName_onSelect = (value2, option2) => {
  // let a = feeNameOptions.value.find((item)=> {return item.value=value})
  // console.log(a.value,a.label)
  // form.name=a.value
  let label = option2.label.split(' -')[0]
  oceanFeeForm.feeName_val = label
  oceanFeeForm.feeName = label
  oceanFeeForm.feeModules = option2.module
  oceanFeeForm.price = option2.price
};
const feeName_change = (value2) => {
  let a = feeNameOptions.value.find((item) => { return item.value = value2 })
  oceanFeeForm.feeName_val = a.label
  oceanFeeForm.feeName = a.label
};
const feeName_blur = () => {
  oceanFeeForm.feeName_val = oceanFeeForm.feeName
};



//开票   防止重复刷新
const invoicenameOptions = ref([]);
const invoicename_onSearch = searchText => {
  clearTimeout(timeout)
  timeout = setTimeout(() => {
    listInvoiceSel({ 'name': searchText }).then(msg => {
      invoicenameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const invoicename_onSelect = (value2, option2) => {
  // let a = invoicenameOptions.value.find((item)=> {return item.value=value})
  // console.log(a.value,a.label)
  // { "code": 0, "data": [{ "value": "825", "label": "厦航厦航厦航厦航", "invoiceState": "0", "type": "" }], "message": "操作成功" }
  let label = option2.label.split(' -')[0]
  oceanFeeForm.invoicename_val = label
  oceanFeeForm.invoicename = label
  oceanFeeForm.invoicestate = option2.invoiceState
};
const invoicename_blur = () => {
  // oceanFeeForm.invoicename_val = oceanFeeForm.invoicename
};
const invoicename_default_onSelect = async (b_type) => {
  await listInvoiceSel({ 'name': '' }).then(msg => {
    invoicenameOptions.value = msg
  }).catch((e) => {
  })
  let b_name = ocean.invoice.company
  if (b_type == '应收') {
  } else if (b_type == '应付') {
    b_name = ocean.invoice.bookingAgent
  }
  if (b_name == null || b_name == undefined || b_name == '') { return }
  let option2 = invoicenameOptions.value.find((item) => {
    return item.label == b_name
  })
  oceanFeeForm.invoicename_val = option2.label
  oceanFeeForm.invoicename = option2.label
  oceanFeeForm.invoicestate = option2.invoiceState
};

let payable_receivable_type = ref('')
/* 打开编辑弹窗 */
const oceanFeeOpenEdit = (record, type_t) => {
  oceanFeeResetFormFields();
  oceanFeeFormRef.value?.clearValidate();
  oceanFeeCurrent.value = record?? {};
  oceanFeeVisible_modal.value = true;
  Object.assign(oceanFeeForm, record ?? {});
  oceanFeeIsUpdate.value = !!record;
  oceanFeeForm.oceanId = oceanId.value
  if (type_t == 'receivable') {
    payable_receivable_type.value = '应收'
    oceanFeeForm.type = '应收'
  }
  if (type_t == 'payable') {
    payable_receivable_type.value = '应付'
    oceanFeeForm.type = '应付'
  }
  if (record == null) {
    invoicename_default_onSelect(payable_receivable_type.value)
    oceanFeeForm.feeName_val = oceanFeeForm.feeName
    oceanFeeForm.currency = "CNY"
    oceanFeeForm.exchangeRate = "1"
  } else {
    oceanFeeForm.invoicename_val = oceanFeeForm.invoicename
    oceanFeeForm.feeName_val = oceanFeeForm.feeName
  }
};

/* 保存编辑 */
const oceanFeeSave = () => {
  if (!oceanFeeFormRef.value) {
    return;
  }
  oceanFeeFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = oceanFeeIsUpdate.value ? updateOceanFee : addOceanFee;
    saveOrUpdate(oceanFeeForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      oceanFeeVisible_modal.value = false;
      oceanFeeReload(ocean);
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<style lang="less" scoped>
@import "@/assets/css/public.less";

.re {
  background-color: @button-pay;
}

.space {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
